package com.efei.jdbc.config;

import com.efei.jdbc.annotation.EnableQuery;
import com.efei.jdbc.dao.SimpleQueryDao;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.beans.Introspector;
import java.util.Map;

public class QueryDaoBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(EnableQuery.class.getName());
        AnnotationAttributes attributes = new AnnotationAttributes(annotationAttributes);
        Class<?> queryDaoFactoryBeanClass = attributes.getClass("queryDaoFactoryBeanClass");

        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition.setBeanClass(queryDaoFactoryBeanClass);
        beanDefinition.setScope(AbstractBeanDefinition.SCOPE_SINGLETON);
        beanDefinition.setPrimary(true);
        registry.registerBeanDefinition(Introspector.decapitalize(queryDaoFactoryBeanClass.getSimpleName()),beanDefinition);
    }
}
